package controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Observable;

import model.UnregisteredUser;
import view.UserRegisterGUI;
import client.CliMessage;
import client.MailMessage;

/**
 * This Class is a Registration window Controller.
 *
 * @author Dmitry
 */
public class RegisterController extends AbstractController implements IValidateInput{

	/** The reg view. */
	private UserRegisterGUI regView;
	
	/** The reg model. */
	private UnregisteredUser regModel;

	/**
	 * Instantiates a new register controller.
	 *
	 * @param registerView the register view
	 * @param registerModel the register model
	 */
	public RegisterController(UserRegisterGUI registerView,UnregisteredUser registerModel ){
		super(registerView,registerModel);
        this.regView = registerView;
        this.regModel = registerModel;
        this.regView.addRegisterActionListener(new RegisterListener());
        this.regView.addCancelActionListener(new CancelListener());
	}
	
	/**
	 * This method validates that mandatory fields were filled 
	 */
	@Override
	public boolean validateInput() {
		if(regView.getFirstName().equals("") || regView.getLastName().equals("") 
				|| regView.getPassword().equals("") || regView.getEmail().equals("")
				|| regView.getAddress().equals("") || regView.getPhone().equals("   -       ")){
			regView.displayWrnMessage("You MUST fill ALL required fields!");
			regView.clearFields();
			return false;
		}
		regView.undisplayWrnMessage();
		return true;
	}
	
	/**
	 * This method gets an answer from the server and calls appropriate methods
	 */
	@Override
	public void update(Observable arg0, Object arg) {
		String msg = new String(((CliMessage)arg).getMessageFromServer());
		
		
		if( msg.equals("#OC:Connection error.") || msg.equals("#OC:Connection closed." ))
		{
			handleConnectionFail();
			return;
		}
		if( msg.equals("#Server: Action success"))
		{
			handleDBRequestSuccess();
			return;
		}
		if(msg.equals("#Server: Action failed" ))
		{
			handleDBRequestFail() ;
			return;
		}
		if(msg.equals("#Server: Null search result"))
		{	
			handleNullSearchResult();
			return;
		}
		if(msg.equals("#Server: Search result"))
		{ 
			handleDBSearchResult((CliMessage)arg);
		}
		
	}

	/**
	 * The listener interface for receiving register events.
	 * This inner class is called whenever the "Register" button is clicked.
	 */
	class RegisterListener implements ActionListener{

		/**
		 *  If all mandatory fields were filled, creates registered customer model and checks whether 
		 *	there is a person with such details in the DB
		 * @see ActionListener
		 */
		@Override
		public void actionPerformed(ActionEvent arg0) {
			if(!validateInput())
				return;
			regModel.setFname(regView.getFirstName());
			regModel.setLname(regView.getLastName());
			regModel.setPassword(regView.getPassword());
			regModel.setEmail(regView.getEmail());
			regModel.setPhone(regView.getPhone());
			regModel.setAddress(regView.getAddress());
			System.out.println(regModel.toString());
			String sql = "search" + "SELECT * " + 
						 "FROM unregisteredcustomer AS UC " + 
						 "WHERE UC.phone = '" + regModel.getPhone() + "'" +
						 " OR UC.email = '" + regModel.getEmail() + "'" + 
						 "UNION " + 
						 "SELECT * " +
						 "FROM unregisteredcustomer AS UC1 " + 
						 "WHERE UC1.fname = '" + regModel.getFname() + "'" +
						 " AND UC1.lname = '" + regModel.getLname() + "'" +
						 " AND UC1.addr = '" + regModel.getAddress() + "'";
			// Send a query to DB
			sendToServer(sql);
			}
	}
	
	/**
	 * The listener interface for receiving cancel events.
	 * This inner class is called whenever the "Cancel" button is clicked - closes register view window.
	 */
	class CancelListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			regView.dispose();
		}
		
	}
	
	/**
	 * This method sends a confirmation email to the user if his registration process succeeded. 
	 */
	@Override
	public void handleDBRequestSuccess() {
		System.out.println("The user has been added successfully!");
		MailMessage send = new MailMessage();
		send.sendMail(regModel.getEmail(),"Welcome","Dear " + regModel.getLname() + " " + regModel.getFname() + " " + ", thank you for your registration to SGI, "
				+ "you will receive a confirmation E-Mail as soon as your account will be approved.\n");
		
		regView.clickbtnCancel();
		}
	
	/**
	 * This method handles a situation when there is no user with entered details in the DB. Then
	 * we add a new registered user to the DB.
	 */
	@Override
	public void handleNullSearchResult() {
		String sql = "adu" + "INSERT unregisteredcustomer (fname,lname,addr,phone,email,requestedPassword,isApprovedByCusSrvc) " + 
				 "VALUES ('" + regModel.getFname()+"'," + 
				 			"'" + regModel.getLname() + "'," + 
				 			"'" + regModel.getAddress() + "'," +
				 			"'" + regModel.getPhone() + "'," +
				 			"'" + regModel.getEmail() + "'," + 
				 			"'" + regModel.getPassword() + "', 0)";
	sendToServer(sql);
	}

	/**
	 * This method handles DB results and checks if there are user with the given details in DB,
	 * if so we print an appropriate warning message.
	 */
	@Override
	public void handleDBSearchResult(CliMessage dbResult) {
		ArrayList<HashMap<String,String>> res = ((CliMessage)dbResult).getSrs();
			if(res.get(0).get("EMAIL").equals(regModel.getEmail())){
					regView.displayWrnMessage("User with this E-mail is already exist!");
					regView.clearFields();
			}
			else if(res.get(0).get("EMAIL").equals(regModel.getEmail()) && res.get(0).get("PHONE").equals(regModel.getPhone()))
			{
				regView.displayWrnMessage("User with this E-mail and Phone number is already exist!");
				regView.clearFields();
			}
			else{
				regView.displayWrnMessage("Such user is already exist! Please try again.");
				regView.clearFields();
			}
		}
}

	
	

